package com.jpmc.refapp.workflow.workitem.handler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.drools.KnowledgeBase;
import org.drools.runtime.StatelessKnowledgeSession;
import org.drools.runtime.process.WorkItem;
import org.drools.runtime.process.WorkItemHandler;
import org.drools.runtime.process.WorkItemManager;

import com.jpmc.refapp.workflow.domain.Request;
import com.jpmc.refapp.workflow.domain.Route;

public class DetermineRoutingHandler implements WorkItemHandler {
	private KnowledgeBase ruleBase;
	
	public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
		
		try
		{
		
			System.out.println("Inside DetermineRoutingHandler...");
			
			HashMap<String, Object> parameterMap =  (HashMap<String, Object>) workItem.getParameters();			
			Request req = (Request)parameterMap.get("req");
			System.out.println("Found Req: "+ req.getRequestId());
			
			ArrayList<Object> sessionFacts = new ArrayList<Object>();	
			StatelessKnowledgeSession session = ruleBase.newStatelessKnowledgeSession();
			//Request req = new Request("101", "ADD", true);
			Route provRoute = new Route();			
			
			sessionFacts.add(req);
			sessionFacts.add(provRoute);
			session.execute(sessionFacts);
			
			System.out.println("provRoute: "+provRoute.getProvRoute());			
	        	
			parameterMap.put("provRoute", provRoute);
			manager.completeWorkItem(workItem.getId(), parameterMap);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}

	public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {
		// TODO Auto-generated method stub

	}

	public void setRuleBase(KnowledgeBase ruleBase) {
		this.ruleBase = ruleBase;
	}

	public KnowledgeBase getRuleBase() {
		return ruleBase;
	}

}
